package com.hl.payServer.controller;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hl.payServer.exception.WepayException;
import com.hl.payServer.model.PageBean;
import com.hl.payServer.model.PayTradeInfo;
import com.hl.payServer.model.ResultModel;
import com.hl.payServer.model.ResultStatus;
import com.hl.payServer.model.enums.TradeType;
import com.hl.payServer.service.PayTradeInfoService;
import com.hl.payServer.util.DateUtil;
import com.hl.payServer.util.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/tradeInfo")
public class TradeInfoController {

    private static final Logger log = LoggerFactory.getLogger(TradeInfoController.class);
    @Autowired
    private PayTradeInfoService payTradeInfoService;

    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public ResultModel list(@RequestParam("data") String data, HttpServletRequest request){
        try {
            HashMap<String,String> jsonObject = JSON.parseObject(data,HashMap.class);
            Preconditions.checkNotNullAndEmpty(jsonObject.get("companyCode"), "companyCode");
            if (jsonObject.get("createTimeStart") != null && DateUtil.checkDateFormatAndValite(jsonObject.get("createTimeStart"), "yyyy-MM-dd HH:mm:ss")==0) {
                throw new IllegalArgumentException("createTimeStart时间参数格式不正确,正确格式例如:yyyy-MM-dd HH:mm:ss");
            }
            if (jsonObject.get("createTimeEnd") != null && DateUtil.checkDateFormatAndValite(jsonObject.get("createTimeEnd"), "yyyy-MM-dd HH:mm:ss")==0) {
                throw new IllegalArgumentException("createTimeEnd时间参数格式不正确,正确格式例如:yyyy-MM-dd HH:mm:ss");
            }
            if (jsonObject.get("payTimeStart") != null && DateUtil.checkDateFormatAndValite(jsonObject.get("payTimeStart"), "yyyy-MM-dd HH:mm:ss")==0) {
                throw new IllegalArgumentException("payTimeStart时间参数格式不正确,正确格式例如:yyyy-MM-dd HH:mm:ss");
            }
            if (jsonObject.get("payTimeEnd") != null && DateUtil.checkDateFormatAndValite(jsonObject.get("payTimeEnd"), "yyyy-MM-dd HH:mm:ss")==0) {
                throw new IllegalArgumentException("payTimeEnd时间参数格式不正确,正确格式例如:yyyy-MM-dd HH:mm:ss");
            }
            HashMap<String,Object> queryMap = new HashMap<String,Object>(jsonObject);
            return ResultModel.ok(payTradeInfoService.queryList(queryMap));
        }catch (IllegalArgumentException illegalArgumentException){
            log.error("支付参数："+data+" 参数错误:参数不符合验证规则,error:"+illegalArgumentException.getMessage());
            return ResultModel.error(ResultStatus.CLIENT_ERROR,"参数错误:参数不符合验证规则,error:"+illegalArgumentException.getMessage());
        } catch (Exception e) {
            log.error("支付参数:"+data+"系统错误:error:"+e.getMessage(), e);
            return ResultModel.error(ResultStatus.SERVER_ERROR,"系统错误:error:"+e.getMessage());
        }
    }

    @RequestMapping(value = "/pay", method = RequestMethod.POST)
    public ResultModel pay(@RequestParam("data") String data, HttpServletRequest request){
        Map<String,Object> params=null;
        try {
            params= JSON.parseObject(data, Map.class);
            if(params.get("tradeType")==null || "".equals(params.get("tradeType").toString())){
                //默认为二维码支付
                params.put("tradeType", TradeType.NATIVE.type());
            }else{
                params.put("tradeType", params.get("tradeType").toString());
            }
            params.put("clientId", getIpAddr(request));
            return payTradeInfoService.pay(params, data);
        }catch (IllegalArgumentException illegalArgumentException){
            log.error("支付参数："+data+" 参数错误:参数不符合验证规则,error:"+illegalArgumentException.getMessage());
            return ResultModel.error(ResultStatus.CLIENT_ERROR,"参数错误:参数不符合验证规则,error:"+illegalArgumentException.getMessage());
        } catch (Exception e) {
            log.error("支付参数:"+data+"系统错误:error:"+e.getMessage(), e);
            return ResultModel.error(ResultStatus.SERVER_ERROR,"系统错误:error:"+e.getMessage());
        }
    }


    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public ResultModel update(@RequestParam("data") String data, HttpServletRequest request){
        PayTradeInfo payTradeInfo = null;
        try {
            payTradeInfo = JSON.parseObject(data, PayTradeInfo.class);
            Preconditions.checkNotNullAndEmpty(payTradeInfo.getTradeNo(), "tradeNo");
            Preconditions.checkNotNullAndEmpty(payTradeInfo.getCompanyCode(), "companyCode");
            PayTradeInfo byTradeNo = payTradeInfoService.findByTradeNo(payTradeInfo.getTradeNo());
            if (!payTradeInfo.getCompanyCode().equals(byTradeNo.getCompanyCode())) {
                return ResultModel.error(ResultStatus.CLIENT_ERROR,"参数错误:companyCode与查询出来的数据所属companyCode不一致,修改失败");
            }
            //修改只能修改以下5种属性的值,其它的属性都是支付相关,接口不允许修改
            PayTradeInfo dbObj = new PayTradeInfo();
            dbObj.setId(byTradeNo.getId());
            dbObj.setBackup1(payTradeInfo.getBackup1());
            dbObj.setBackup2(payTradeInfo.getBackup2());
            dbObj.setBackup3(payTradeInfo.getBackup3());
            dbObj.setBackup4(payTradeInfo.getBackup4());
            dbObj.setBackup5(payTradeInfo.getBackup5());
            dbObj.initUpdateTime();
            ResultModel res = payTradeInfoService.update(dbObj);
            res.setContent(null);
            return res;
        }catch (IllegalArgumentException illegalArgumentException){
            log.error("支付参数："+data+" 参数错误:参数不符合验证规则,error:"+illegalArgumentException.getMessage());
            return ResultModel.error(ResultStatus.CLIENT_ERROR,"参数错误:参数不符合验证规则,error:"+illegalArgumentException.getMessage());
        } catch (Exception e) {
            log.error("支付参数:"+data+"系统错误:error:"+e.getMessage(), e);
            return ResultModel.error(ResultStatus.SERVER_ERROR,"系统错误:error:"+e.getMessage());
        }
    }


    /**
     * 查询三方支付订单，包括支付宝、微信、通联支付、ecod
     * @param data 订单信息
     * 参数说明：
     * 单号： platformPayNo 或 code + appPlatform + outTradeNo + payChannle
     * 单号说明：
     * platformPayNo:PayTradeInfo表里的tradeNo
     * outTradeNo:PayTradeInfo表里的bizNo
     * 如果都有，以 platformPayNo 为准
     *
     */
    @RequestMapping(value = "/third", method = RequestMethod.POST)
    public ResponseEntity<ResultModel> third(@RequestParam("data") String data){
        HashMap<String,Object> params=null;
        try {
            params = JSON.parseObject(data, HashMap.class);
            return new ResponseEntity(ResultModel.ok(payTradeInfoService.queryThird(params, null)), HttpStatus.OK);
        }catch (IllegalArgumentException illegalArgumentException){
            log.error("参数："+params.toString()+" 参数错误:参数不符合验证规则,error:"+illegalArgumentException.getMessage());
            return new ResponseEntity(ResultModel.error(ResultStatus.CLIENT_ERROR," 参数错误:参数不符合验证规则,error:"+illegalArgumentException.getMessage()), HttpStatus.OK);
        }catch (NullPointerException nullPointerException){
            log.error("参数:"+params.toString()+" 参数错误:存在空值,error:"+nullPointerException.getMessage());
            return new ResponseEntity(ResultModel.error(ResultStatus.CLIENT_ERROR," 参数错误:存在空值,error:"+nullPointerException.getMessage()), HttpStatus.OK);
        }catch (WepayException exception){
            log.error("参数:"+params.toString()+"支付错误:error:"+exception.getMessage());
            return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR,"支付错误:error:"+exception.getMessage()), HttpStatus.OK);
        }catch (Exception exception){
            log.error("参数:"+data+"系统错误:error:"+exception.getMessage());
            return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR,"系统错误:error:"+exception.getMessage()), HttpStatus.OK);
        }
    }









    /**
     * 获取访问者IP
     *
     * 在一般情况下使用Request.getRemoteAddr()即可，但是经过nginx等反向代理软件后，这个方法会失效。
     *
     * 本方法先从Header中获取X-Real-IP，如果不存在再从X-Forwarded-For获得第一个IP(用,分割)，
     * 如果还不存在则调用Request .getRemoteAddr()。
     *
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) throws Exception{
        String ip = request.getHeader("X-Real-IP");
        if (!isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }
        ip = request.getHeader("X-Forwarded-For");
        if (!isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个IP值，第一个为真实IP。
            int index = ip.indexOf(',');
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        }
        ip = request.getRemoteAddr();
        if(!isBlank(ip) && !"unknown".equalsIgnoreCase(ip)){
            return ip;
        }
        return "127.0.0.1";
    }

    public static boolean isBlank(String str) {
        int strLen;
        if (str != null && (strLen = str.length()) != 0) {
            for(int i = 0; i < strLen; ++i) {
                if (!Character.isWhitespace(str.charAt(i))) {
                    return false;
                }
            }

            return true;
        } else {
            return true;
        }
    }
}
